//
//  RetrievePswViewController.m
//  HQJFacilitator
//
//  Created by mymac on 2016/10/19.
//  Copyright © 2016年 Fujian first time iot technology investment co., LTD. All rights reserved.
//

#import "RetrievePswViewController.h"

static NSString * kAlphaNum = @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";


@interface RetrievePswViewController () <UITextFieldDelegate>
@property (nonatomic,strong) UITextField *idTextField;
@property (nonatomic,strong) UITextField *mobileTextField;
@property (nonatomic,strong) UITextField *codeTextField;
@property (nonatomic,strong) JKCountDownButton *codeBtn;
@property (nonatomic,strong) UIButton *okBtn;
@property (nonatomic,strong) UIImageView *titImageView;
@property (nonatomic,strong) UILabel *nameLabel;
@property (nonatomic,strong) UILabel *NewPswLabel;
@property (nonatomic,strong) UITextField *NewPswTextField;
@property (nonatomic,strong)NSTimer *clockTimer;
@property (nonatomic,assign)NSInteger seconds;
@end

@implementation RetrievePswViewController

-(UITextField *)codeTextField {
    if(!_codeTextField){
        _codeTextField = [[UITextField alloc]init];
        _codeTextField.keyboardType = UIKeyboardTypeNumberPad;

        _codeTextField.borderStyle = UITextBorderStyleRoundedRect;
        _codeTextField.placeholder = @"请输入验证码";
        [self.view addSubview:_codeTextField];
    }
    
    return _codeTextField;
}

-(UIButton *)codeBtn {
    if (!_codeBtn) {
        _codeBtn = [JKCountDownButton buttonWithType:UIButtonTypeCustom];
        _codeBtn.backgroundColor = [ManagerEngine getColor:@"00ccb8"];
        [_codeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
        _codeBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        _codeBtn.layer.masksToBounds = YES;
        _codeBtn.layer.cornerRadius = 5;
        [self.view addSubview:_codeBtn];
    }
    
    return _codeBtn;
}

-(UIButton *)okBtn {
    
    if (!_okBtn) {
        _okBtn = [JKCountDownButton buttonWithType:UIButtonTypeCustom];
        _okBtn.backgroundColor = [ManagerEngine getColor:@"8ae6dc"];
        [_okBtn setTitle:@"确定" forState:UIControlStateNormal];
        _okBtn.layer.masksToBounds = YES;
        _okBtn.layer.cornerRadius = 5;
        [self.view addSubview:_okBtn];
    }
    
    return _okBtn;
}

-(UIImageView *)titImageView {
    
    if (!_titImageView) {
        _titImageView = [[UIImageView alloc]init];
        _titImageView.image = [UIImage imageNamed:@"man"];
        [self.view addSubview:_titImageView];
    }
    
    return _titImageView;
}

-(UILabel *)nameLabel {
    if (!_nameLabel) {
        _nameLabel = [[UILabel alloc]init];
        _nameLabel.font = [UIFont systemFontOfSize:12];
        _nameLabel.textColor = [ManagerEngine getColor:@"f54949"];
        [self.view addSubview:_nameLabel];
    }
    
    
    return _nameLabel;
}

-(UILabel *)NewPswLabel {
    if (!_NewPswLabel) {
        _NewPswLabel = [[UILabel alloc]init];
        _NewPswLabel.text = @"新密码:";
        _NewPswLabel.font = [UIFont systemFontOfSize:17];
        [self.view addSubview:_NewPswLabel];
    }
    
    
    return _NewPswLabel;
}

-(UITextField *)NewPswTextField {
    
    if (!_NewPswTextField) {
       
        _NewPswTextField = [[UITextField alloc]init];
        _NewPswTextField.borderStyle = UITextBorderStyleRoundedRect;
        _NewPswTextField.keyboardType = UIKeyboardTypeNumberPad;
        _NewPswTextField.secureTextEntry = YES;
        _NewPswTextField.delegate = self;
        if([self.title isEqualToString:@"找回交易密码"]){
            _NewPswTextField.placeholder =@"新交易密码(限6位)";
            _NewPswTextField.keyboardType = UIKeyboardTypeNumberPad;


        } else {
            _NewPswTextField.placeholder =@"新登录密码(限6到12位)";
            _NewPswTextField.keyboardType = UIKeyboardTypeASCIICapable;

        }
        [self.view addSubview:_NewPswTextField];
    }
    
    
    return _NewPswTextField;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor groupTableViewBackgroundColor];
    
    [self RetievePswCreatUI];
    [self retrieveSignal];
}

#pragma mark --
#pragma mark --- 视图内容
-(void)RetievePswCreatUI {
    NSArray *titleAry = @[@"身份证:",@"手机号:"];
    NSArray *FieldAry = @[@"请输入身份证号码",@"请输入手机号"];
    CGFloat TitleSize = [ManagerEngine setTextWidthStr:titleAry[0] andFont:[UIFont systemFontOfSize:17]];
    for (NSInteger i=0; i<2; i++) {
        
        UILabel *titleLabel = [[UILabel alloc]init];
        titleLabel.font = [UIFont systemFontOfSize:17];
        titleLabel.frame = CGRectMake(EDGE, i%2*(20+40*1.5)+25+NAVHEIGHT, TitleSize, 20);
        titleLabel.text = titleAry[i];
        [self.view addSubview:titleLabel];
        
        UITextField *textField = [[UITextField alloc]init];
        textField.borderStyle = UITextBorderStyleRoundedRect;
        textField.keyboardType = UIKeyboardTypeNumberPad;
        textField.tag = i;
        textField.delegate = self;
        textField.frame = CGRectMake(EDGE+5+TitleSize,i%2*(44+20*1.5)+EDGE+NAVHEIGHT, WIDTH-(EDGE*2)-TitleSize-5, 44);
        textField.placeholder = FieldAry[i];
        [self.view addSubview:textField];
        if (textField.tag == 0) {
            _idTextField = textField;
            _idTextField.keyboardType = UIKeyboardTypeASCIICapable;

            
        } else {
            
            _mobileTextField = textField;
            if ([self.title isEqualToString:@"找回交易密码"]) {
                textField.text = [NSString stringWithFormat:@"%@",Mmobile];

            }
        }
    }
    
    
//    self.titImageView.sd_layout.leftSpaceToView(self.view,WIDTH-EDGE-12).topSpaceToView(_idTextField,20).heightIs(12).widthIs(12);
    
    
    
    self.codeTextField.sd_layout.leftSpaceToView(self.view,EDGE).topSpaceToView(_mobileTextField,20*1.5).heightIs(44).widthIs(WIDTH-100-(EDGE*2)-10);
    
    self.codeBtn.sd_layout.leftSpaceToView(self.codeTextField,10).topEqualToView(self.codeTextField).heightIs(44).widthIs(100);
    
    self.NewPswLabel.sd_layout.leftSpaceToView(self.view,EDGE).topSpaceToView(self.codeTextField,25*1.5).heightIs(20).widthIs(TitleSize);
    
    self.NewPswTextField.sd_layout.leftSpaceToView(self.NewPswLabel,5).topSpaceToView(self.codeTextField,15*2).heightIs(44).widthIs(WIDTH-(EDGE *2 )-5-TitleSize);
    
    
    self.okBtn.sd_layout.leftSpaceToView(self.view,EDGE).topSpaceToView(self.NewPswTextField,30*1.5).heightIs(44).widthIs(WIDTH-(EDGE*2));
    
 
  
    
}

-(void)clickBTn {
    
    HQJLog(@"获取验证码....");
    
}


#pragma mark --
#pragma mark --- 信号创建
-(void)retrieveSignal {
    
    RACSignal * idtextSignal = [_idTextField.rac_textSignal map:^id(id value) {
        return @([ManagerEngine validateIdentityCard:value]);
    }];
    
    RACSignal *moblieSignal = [_mobileTextField.rac_textSignal map:^id(id value) {
        return @([ManagerEngine valiMobile:value]);
    }];
    
    RACSignal *codeSignal = [self.codeTextField.rac_textSignal map:^id(id value) {
        return @([self isCode:value]);
    }];
    
    
    RACSignal *upIDSignal = [RACSignal combineLatest:@[idtextSignal]reduce:^id(NSNumber *idCard){
        return @([idCard boolValue]);
    }];
    
    [upIDSignal subscribeNext:^(NSNumber *x) {
     
        if ([x boolValue]) {
            [self idCardRequst];

        } else {
            self.nameLabel.text = @"";
            
        }
        [self upLayout];
        
    }];

    
    
    RACSignal *upSignal = [RACSignal combineLatest:@[idtextSignal,moblieSignal,codeSignal]reduce:^id(NSNumber *idCard,NSNumber *moblie,NSNumber *code){
        return @([idCard boolValue] && [moblie boolValue]&&[code boolValue]);
    }];
    
    [upSignal subscribeNext:^(NSNumber *x) {
        self.okBtn.enabled = [x boolValue];
        if ([x boolValue]) {
            
            self.okBtn.backgroundColor = [ManagerEngine getColor:@"00ccb8"];

        } else {
            self.okBtn.backgroundColor = [ManagerEngine getColor:@"8ae6dc"];

        }
        
        
        
    }];

            
    [self.codeBtn countDownButtonHandler:^(JKCountDownButton*sender, NSInteger tag) {
                
                if([ManagerEngine valiMobile:_mobileTextField.text] == YES) {
 
                    static NSString *typeStr;
                    if ([self.title isEqualToString:@"找回交易密码"]) {
                      typeStr= @"getTradePwdSMS";
                    } else {
                      typeStr = @"getLoginPwdSMS";
                    }
                    [RequestEngine HQJFacilitatorRequestDetailsUrl:[NSString stringWithFormat:@"%@%@/mobile/%@/identitynum/%@",AppOrg_URL,typeStr,_mobileTextField.text,_idTextField.text] complete:^(NSDictionary *dic) {
                        HQJLog(@"收到的验证码是:%@",dic);
                        if ([dic[@"error"]integerValue] != 0) {
                            [ManagerEngine homeSvpStr:dic[@"result"][@"errmsg"] andcenterView:self.view andStyle:promptViewDefault];
                        }else {
                            sender.enabled = NO;
                            //        sender.backgroundColor = [ManagerEngine getColor:@"8ae6dc"];
                            
                            [sender startCountDownWithSecond:60];
                            
                            [sender countDownChanging:^NSString *(JKCountDownButton *countDownButton,NSUInteger second) {
                                NSString *title = [NSString stringWithFormat:@"剩余%zd秒",second];
                                return title;
                            }];

                        }
                        
                        
                    } andError:^(NSError *error) {
                        
                    } ShowHUD:NO];
                    [sender countDownFinished:^NSString *(JKCountDownButton *countDownButton, NSUInteger second) {
                        
                        countDownButton.enabled = YES;
                        return @"点击重新获取";
                        
                    }];
                    
                }else {
                    [ManagerEngine homeSvpStr:@"请核对手机号后重试" andcenterView:self.view andStyle:promptViewDefault];
                    
                }
                
               
                
            }];
            

            
        
    
    [[self.okBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        if([self.title isEqualToString:@"找回登录密码"]) {
            if (self.NewPswTextField.text.length<=12 &&self.NewPswTextField.text.length>=6) {
                [self okRequst];
                
            } else {
                [ManagerEngine homeSvpStr:@"你的密码长度不符合标准" andcenterView:self.view andStyle:promptViewDefault];
                
            }
        } else {
            if (self.NewPswTextField.text.length==6) {
                [self okRequst];
                
            } else {
                [ManagerEngine homeSvpStr:@"你的密码长度不符合标准" andcenterView:self.view andStyle:promptViewDefault];
                
            }
            
        }
        
        
    }];
    
}

#pragma mark --
#pragma mark --- 验证码
-(BOOL)isCode:(NSString *)text {
    if (text.length>0) {
        return YES;
    } else {
        return NO;
        
    }
    
    
}



#pragma mark --
#pragma mark --- 更新视图
-(void)upLayout {
    CGFloat nameSize = [ManagerEngine setTextWidthStr:self.nameLabel.text andFont:[UIFont systemFontOfSize:12]];
    if ([self.nameLabel.text isEqualToString:@""]) {
         self.titImageView.sd_layout.leftSpaceToView(self.view,WIDTH-EDGE-12-nameSize).topSpaceToView(_idTextField,10).heightIs(12).widthIs(12);
    } else {
         self.titImageView.sd_layout.leftSpaceToView(self.view,WIDTH-EDGE-2-12-nameSize).topSpaceToView(_idTextField,10).heightIs(12).widthIs(12);
    }
    
   
                                                
                                                
                                                
    self.nameLabel.sd_layout.leftSpaceToView(self.titImageView,2).topEqualToView(self.titImageView).heightIs(12).widthIs(nameSize);
    
    
}


#pragma mark --
#pragma mark ---身份证请求名字
-(void)idCardRequst {
    
    NSString *urlStr = [NSString stringWithFormat:@"%@getRealname/identitynum/%@/membertype/originator",Api_URL,_idTextField.text];
    [RequestEngine HQJFacilitatorRequestDetailsUrl:urlStr complete:^(NSDictionary *dic) {
        if ([dic[@"error"] integerValue] == 0) {
         
                self.nameLabel.text = [NSString stringWithFormat:@"%@",dic[@"result"][@"realname"]];
            if (![self.nameLabel.text isEqualToString:@""]){
                [ManagerEngine dismissHomeSvP];
            }
//            HQJLog(@"获取的姓名是:%@",str);

            
            [self upLayout];
        } else {
              [ManagerEngine homeSvpStr:dic[@"result"][@"errmsg"] andcenterView:self.view andStyle:promptViewDefault];
        }
        
        
    } andError:^(NSError *error) {
        
    } ShowHUD:NO];
    
}


#pragma mark --
#pragma mark ---提交请求
-(void)okRequst {
    
    
    
    static NSString *urlStr;
    if ([self.title isEqualToString:@"找回交易密码"]) {
        urlStr = [NSString stringWithFormat:@"%@getPwdAction/inputCode/%@/pwdtype/tradepwd/mobile/%@/newpwd/%@",AppOrg_URL,_codeTextField.text,_mobileTextField.text,_NewPswTextField.text];

    } else {
        urlStr = [NSString stringWithFormat:@"%@getPwdAction/inputCode/%@/pwdtype/loginpwd/mobile/%@/newpwd/%@",AppOrg_URL,_codeTextField.text,_mobileTextField.text,_NewPswTextField.text];

    }
       [RequestEngine HQJFacilitatorRequestDetailsUrl:urlStr complete:^(NSDictionary *dic) {
        HQJLog(@"提交:%@",dic);
        if([dic[@"error"]integerValue] == 0){
            [ManagerEngine customAlert:@"成功找回,请妥善保管新密码" andViewController:self isBack:YES];
        }else {
            [ManagerEngine homeSvpStr:dic[@"result"][@"errmsg"] andcenterView:self.view andStyle:promptViewFadeAway];
        }
        
        
    } andError:^(NSError *error) {
        
    } ShowHUD:YES];
    
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    if (textField == _mobileTextField) {
        if ([self.title isEqualToString:@"找回交易密码"]) {
            return NO;
        } else {
            return YES;
        }
        
    }
    return YES;
}


#pragma mark --
#pragma mark ---UITextField Delegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;
{  //string就是此时输入的那个字符 textField就是此时正在输入的那个输入框 返回YES就是可以改变输入框的值 NO相反
    if (textField == self.NewPswTextField) {
     
        NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:kAlphaNum] invertedSet];
        NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
        return [string isEqualToString:filtered];
        
    }
    if (textField == _NewPswTextField) {
        
        if ([self.title isEqualToString:@"找回登录密码"]) {
            
            if ([string isEqualToString:@""]) {
                return YES;
            } else {
                return textField.text.length>=12?NO:YES;
                
            }
            
            
        } else {
            
            if ([string isEqualToString:@""]) {
                return YES;
            } else {
                return textField.text.length>=6?NO:YES;
                
            }
            
            
        }
    }

    
    return YES;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
